﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Project.Repositories;
using PmSoft;
using PmSoft.Exceptions;

namespace Modules.Project;

/// <summary>
/// 项目参建企业非正常工资单授权服务
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class ProjectCorpWageAuthService
{
    private readonly ProjectCorpWageAuthRepository projectCorpWageAuthRepository;

    public ProjectCorpWageAuthService(ProjectCorpWageAuthRepository projectCorpWageAuthRepository)
    {
        this.projectCorpWageAuthRepository = projectCorpWageAuthRepository;
    }

    /// <summary>
    /// 项目参建企业非正常工资单授权表单详情
    /// </summary>
    /// <param name="id">主键</param>
    /// <returns></returns>
    public ProjectCorpWageAuth? Get(int id)
    {
        return projectCorpWageAuthRepository.Get(id);
    }

    public IEnumerable<ProjectCorpWageAuth> GetProjectCorpWageAuths(IEnumerable<int> ids)
    {
        return projectCorpWageAuthRepository.PopulateEntitiesByEntityIds(ids);
    }

    /// <summary>
    /// 批量删除，根据id
    /// </summary>
    /// <param name="ids">id的集合</param>
    public void Deleted(IEnumerable<int> ids)
    {
        foreach (int id in ids)
        {
            Delete(id);
        }
    }

    /// <summary>
    /// 单个删除
    /// </summary>
    /// <param name="id">主键</param>
    public void Delete(int id)
    {
        projectCorpWageAuthRepository.DeleteByEntityId(id);
    }

    /// <summary>
    /// 创建项目参建企业非正常工资单授权
    /// </summary>
    /// <param name="entity">实体对象</param>
    public void Create(ProjectCorpWageAuth entity)
    {
        if (projectCorpWageAuthRepository.ExistsByProjetIdCorpIdMonth(entity.ProjectId, entity.CorpId, entity.Month)) throw new BusinessException("当月已存在非正常工资单");
        projectCorpWageAuthRepository.Insert(entity);
    }

    /// <summary>
    /// 编辑项目参建企业非正常工资单授权
    /// </summary>
    /// <param name="entity">实体对象</param>
    public void Update(ProjectCorpWageAuth entity)
    {
        projectCorpWageAuthRepository.Update(entity);
    }

    /// <summary>
    /// 项目参建企业非正常工资单授权分页列表
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <param name="pageIndex">当前页码</param>
    /// <param name="pageSize">每页显示条数</param>
    /// <returns></returns>
    public IPagedList<ProjectCorpWageAuth> GetProjectCorpWageAuths(ProjectCorpWageAuthQuery query, int pageIndex, int pageSize)
    {
        return projectCorpWageAuthRepository.GetProjectCorpWageAuths(query, pageIndex, pageSize);
    }

    public ProjectCorpWageAuth? GetProjectCorpWageAuthByProjectIdAndCorpIdAndMonth(int projectId, int corpId, int month)
    {
        var data = projectCorpWageAuthRepository.GetProjectCorpWageAuthByProjectId(projectId).Where(a => a.CorpId == corpId);
        return data.FirstOrDefault(a => a.Month == month);
    }
}